package com.qf.servlet;

import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.AdminService;
import com.qf.service.UserService;
import com.qf.service.impl.AdminServiceImpl;
import com.qf.service.impl.UserServiceImp;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/register")
public class userCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding ( "utf-8" );

        response.setContentType ( "text/html;charest=utf-8" );
        //获取前台输入验证码
        String userCode = request.getParameter ( "userCode" );
        //获取服务器端储存的验证码

        HttpSession session = request.getSession ( );
        String checkcode = (String) session.getAttribute ( "CHECKCODE_SERVER" );

        session.removeAttribute ( "CHECKCODE_SERVER" );

        if(userCode==null|| !userCode.equals ( checkcode )){
            request.setAttribute ( "msg","验证码输入错误" );
            request.getRequestDispatcher ( "/jsp/msg.jsp" ).forward ( request,response );
        }
        //如果验证码一致  封装前台用户

        User user =new User ();
        Map<String, String[]> map = request.getParameterMap ( );

        ConvertUtils.register(new MyConvert (), Date.class);

        try {
            BeanUtils.populate ( user,map );
        } catch (IllegalAccessException e) {
            e.printStackTrace ( );
        } catch (InvocationTargetException e) {
            e.printStackTrace ( );
        }
        //通过工具类生成UID并封装
        user.setUid ( UUIDUtils.getId () );
        //密码加密
        String password = request.getParameter ( "password" );
        user.setPassword ( MD5Utils.md5 ( password ) );
        //生成邮件的激活码

        user.setCode (UUIDUtils.getCode ());


        UserService userService = new UserServiceImp ();
        userService.addUser(user);

        request.setAttribute("msg","恭喜您,注册成功,请激活邮箱");
        request.getRequestDispatcher ( "/jsp/msg.jsp" ).forward ( request,response );




    }

    protected void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
        doPost ( request,response );
    }
}
